package com.xiaofen.license.util;

import java.io.*;
import java.net.URLDecoder;

/**
 * [一句话描述该类的功能]
 *
 * @author zhang
 * @createDate: 2021/1/22 16:24
 * @version:1.0
 * @updateUser:[修改人]
 * @updateDate:[修改时间]
 * @updateRemark:[修改备注]
 */
public class FileUtils {

    /**
     * 获得类的基路径，打成jar包也可以正确获得路径
     * @return
     */
    public static String getBasePath(){
        /*
        /D:/zhao/Documents/NetBeansProjects/docCompare/build/classes/
        /D:/zhao/Documents/NetBeansProjects/docCompare/dist/bundles/docCompare/app/docCompare.jar
        */
        String filePath = FileUtils.class.getProtectionDomain().getCodeSource().getLocation().getFile();
//        String filePath = System.getProperty("user.dir");


        if (filePath.endsWith(".jar")){
            filePath = filePath.substring(0, filePath.lastIndexOf("/"));
            try {
                filePath = URLDecoder.decode(filePath, "UTF-8"); //解决路径中有空格%20的问题
            } catch (UnsupportedEncodingException ex) {

            }

        }
        File file = new File(filePath);
        filePath = file.getAbsolutePath();
        return filePath;
    }

    /**
     * 读取txt文件
     * */
    public static String readTxt(File file) throws IOException {
        String s = "";
        InputStreamReader in = new InputStreamReader(new FileInputStream(file),"UTF-8");
        BufferedReader br = new BufferedReader(in);
        StringBuffer content = new StringBuffer();
        while ((s = br.readLine()) != null){
            content = content.append(s);
        }
        return content.toString();
    }

    public static void main(String[] args) throws Exception {
        System.out.println(getBasePath());
    }
}
